package edu.cuc.chap02.lianxi.l1.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;

public class TimeClientHandler1 extends ChannelInboundHandlerAdapter {
    final ByteBuf byteBuf;
    public TimeClientHandler1() {
        byte[] message = "QUERY ORDER TIME".getBytes();
        byteBuf = Unpooled.buffer(message.length);
        byteBuf.writeBytes(message);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] res = new byte[buf.readableBytes()];
        buf.readBytes(res);
        String message = new String(res);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        message = simpleDateFormat.format(Long.valueOf(message));
        System.out.println(message);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
